<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import $api from "@/api/index.js"
	import $store from "@/store/index.js"
	export default {
		data() {
			return {
				timer: null
			}
		},
		async mounted() {
			// #ifdef H5
			if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
				window.entryUrl = window.location.href.split('#')[0]
			}
			if (window.location.href.indexOf('?#') < 0) {
				window.location.href = window.location.href.replace("#", "?#");
			}
			// #endif
			console.log('App mounted')
		},
		async onLaunch() {
			let configInfo = uni.getStorageSync('configInfo') || ''
			if (configInfo) {
				$store.commit('updateConfigItem', {
					key: 'configInfo',
					val: configInfo
				})
			}
			let isGzhLogin = uni.getStorageSync('isGzhLogin') || false
			$store.commit('updateUserItem', {
				key: 'isGzhLogin',
				val: isGzhLogin
			})
			let arr = ['autograph', 'userInfo', 'location', 'appLogin', 'loginType']
			arr.map(key => {
				let val = uni.getStorageSync(key) || ''
				// #ifdef H5
				val = isGzhLogin ? val : ''
				// #endif
				$store.commit('updateUserItem', {
					key,
					val
				})
				// #ifdef APP-PLUS
				if (key == 'userInfo') {
					$store.commit('updateUserItem', {
						key: 'isShowLogin',
						val: val && val.id ? false : true
					})
				}
				// #endif
			})
			let {
				commonOptions
			} = this
			let {
				coach_id = 0
			} = commonOptions
			if (coach_id) {
				commonOptions.coach_id = 0
				$store.commit('updateUserItem', {
					key: 'commonOptions',
					val: commonOptions
				})
			}
			this.initIndex()
			console.log('App onLaunch')
		},
		async onShow() {
			if (this.timer) {
				clearInterval(this.timer)
			}
			let {
				coach_position = 0
			} = this.userInfo
			let {
				id: coachId = 0,
				status = 0
			} = this.coachInfo
			if (coach_position == 1) {
				if (!coachId) {
					await this.getCoachInfo()
				}
				$store.commit('updateUserItem', {
					key: 'locationChange',
					val: true
				})
			}
			uni.onNetworkStatusChange((res) => {
				let {
					isConnected
				} = res
				if (isConnected) return
				let methodArr = ['updateServiceItem', 'updateTechnicianItem']
				methodArr.map(item => {
					$store.commit(item, {
						key: 'pageActive',
						val: false
					})
				})
			})
		},
		async onHide() {
			console.log('App Hide')
			let {
				coach_position = 0
			} = this.userInfo
			let {
				status = 0
			} = this.coachInfo
			if (!coach_position || status != 2) return
			$store.commit('updateUserItem', {
				key: 'locationChange',
				val: false
			})
			// #ifdef H5
			if (this.$jweixin.isWechat()) {
				await this.$jweixin.wxReady2();
				this.toHidePage()
				this.timer = setInterval(() => {
					this.toHidePage()
				}, 60000)
			}
			// #endif
		},
		onUnload() {
			uni.offLocationChange((res) => {
				console.log("====offLocationChange onUnload", res)
			})
		},
		watch: {
			locationChange(newVal, oldVal) {
				if (newVal) {
					uni.startLocationUpdate({
						complete: msg => console.log(`startLocationUpdate API complete`, msg)
					})
				} else {
					uni.stopLocationUpdate({
						complete: msg => console.log(`stopLocationUpdate API complete`, msg)
					})
				}
			},
			'configInfo.attendant_name'(newVal, oldVal) {
				if (newVal) {
					this.mergeLocaleMessage()
				}
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			old_attendant_name: state => state.config.old_attendant_name,
			commonOptions: state => state.user.commonOptions,
			locationChange: state => state.user.locationChange,
			locationChangeUnix: state => state.user.locationChangeUnix,
			userInfo: state => state.user.userInfo,
			coachInfo: state => state.user.coachInfo,
		}),
		methods: {
			...mapActions(['getConfigInfo', 'getUserInfo', 'getCoachInfo']),
			async initIndex() {
				let that = this
				let {
					coach_position = 0
				} = that.userInfo
				uni.onLocationChange((res) => {
					console.log("====onLocationChange", res)
					let {
						latitude: lat,
						longitude: lng
					} = res
					that.toChangeLocation({
						lat,
						lng
					})
				})
				if (coach_position == 1) {
					let {
						id: coachId = 0
					} = that.coachInfo
					if (!coachId) {
						await that.getCoachInfo()
					}
					$store.commit('updateUserItem', {
						key: 'locationChange',
						val: true
					})
				}
				let {
					primaryColor = '',
						plugAuth = {},
						tabBar = []
				} = that.configInfo
				let mineInd = tabBar.findIndex(item => {
					return item.id == 5
				})
				console.log(mineInd, "======mineInd")
				// if ((primaryColor && plugAuth.length > 0) || mineInd != -1) return
				await that.getConfigInfo()
			},
			async mergeLocaleMessage() {
				let zh = JSON.parse(JSON.stringify(this.$i18n.messages.zh))
				let {
					attendant_name: name,
				} = this.configInfo
				let oldName = this.old_attendant_name
				let reg = new RegExp(oldName, 'g')
				for (let i in zh.action) {
					if (zh.action[i].includes(oldName)) {
						zh.action[i] = zh.action[i].replace(reg, name)
					}
				}
				this.$i18n.mergeLocaleMessage('zh', zh)
				$store.commit('updateConfigItem', {
					key: 'old_attendant_name',
					val: name
				})
				// console.log(this.$t('action.attendantName'), this.$i18n.messages.zh, "=====");
			},
			async toHidePage() {
				let {
					latitude: lat,
					longitude: lng
				} = await this.$jweixin.getWxLocation()
				if (lat && lng) {
					let val = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
					$store.commit('updateUserItem', {
						key: 'locationChangeUnix',
						val
					})
					this.toChangeLocation({
						lat,
						lng
					})
				}
			},
			async toChangeLocation(param) {
				let {
					lat,
					lng
				} = param
				let {
					id = 0,
						coach_position = 0
				} = this.userInfo
				let {
					lat: coach_lat,
					lng: coach_lng,
					status = 0
				} = this.coachInfo
				let {
					locationChangeUnix
				} = this
				let curUnix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
				let second = 3
				// #ifdef APP-PLUS
				second = 1
				// #endif
				// console.log(curUnix, locationChangeUnix, curUnix - locationChangeUnix,
				// 	"=====curUnix - locationChangeUnix")
				let isMin = curUnix - locationChangeUnix <= second || curUnix - locationChangeUnix >= 60
				let isSame = coach_lat * 1 == lat && coach_lng * 1 == lng
				// console.log(lat, lng, coach_position, isMin, isSame, "=====lat, lng, coach_position, isMin")
				if (!coach_position || status != 2 || !isMin || isSame) return

				let val = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
				$store.commit('updateUserItem', {
					key: 'locationChangeUnix',
					val
				})

				let key = `${lat},${lng}`
				try {
					let data = await this.$api.base.getMapInfo({
						location: key
					})
					let {
						status,
						result
					} = JSON.parse(data)
					if (status == 0) {
						let {
							address
						} = result
						console.log("toChangeLocation==>", `${lat}-${lng}-${address}`)
						await this.$api.technician.coachUpdate({
							lat,
							lng,
							address
						})
						await this.getCoachInfo()
					}
				} catch (e) {
					console.log('=====getMapInfo catch')
					uni.stopLocationUpdate({
						complete: msg => console.log(`stopLocationUpdate API complete`, msg)
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	@import "@/uni_modules/uview-ui/index.scss";
	@import "/styles/index.wxss";

	/* #ifdef H5 */
	uni-page-head {
		display: none;
	}

	/* #endif */

	page {
		font-size: 28rpx;
		color: #222;
		line-height: 1.5;
		background: #F6F6F6;
		font-family: -apple-system-font, Helvetica Neue, Helvetica, sans-serif;
	}

	input {
		// font-family: PingFangSC-Medium, PingFang SC, -apple-system-font, Helvetica Neue, Helvetica, sans-serif;
	}

	input::-webkit-input-placeholder {
		/* WebKit browsers */
		color: #A9A9A9;
	}

	input:-moz-placeholder {
		/* Mozilla Firefox 4 to 18 */
		color: #A9A9A9;
	}

	input::-moz-placeholder {
		/* Mozilla Firefox 19+ */
		color: #A9A9A9;
	}

	input:-ms-input-placeholder {
		/* Internet Explorer 10+ */
		color: #A9A9A9;
	}

	view {
		box-sizing: border-box;
	}

	image {
		display: block;
	}

	.h5-image {
		background-position: center center;
		background-size: cover;
		background-repeat: no-repeat;
	}

	/*隐藏滚动条*/
	::-webkit-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
	}

	/* #ifdef MP-BAIDU */
	.swan-button.swan-button-radius-ios {
		border-radius: 0;
	}

	/* #endif */
	
	
	// his add
	.font10 {
		font-size: 10rpx;
	}
	
	.font12 {
		font-size: 12rpx;
	}
	
	.font14 {
		font-size: 14rpx;
	}
	
	.font16 {
		font-size: 16rpx;
	}
	
	.font18 {
		font-size: 18rpx;
	}
	
	.font20 {
		font-size: 20rpx;
	}
	
	.font22 {
		font-size: 22rpx;
	}
	
	.font24 {
		font-size: 24rpx;
	}
	
	.font26 {
		font-size: 26rpx;
	}
	
	.font28 {
		font-size: 28rpx;
	}
	
	.font30 {
		font-size: 30rpx;
	}
	
	.font32 {
		font-size: 32rpx;
	}
	
	.font34 {
		font-size: 34rpx;
	}
	
	.font36 {
		font-size: 36rpx;
	}
	
	.font40 {
		font-size: 40rpx;
	}
	
	.font42 {
		font-size: 42rpx;
	}
	
	.font44 {
		font-size: 44rpx;
	}
	
	.font48 {
		font-size: 48rpx;
	}
	
	.font500 {
		font-weight: 500;
	}
	
	.font600 {
		font-weight: 600;
	}
	
	.font700 {
		font-weight: 700;
	}
	
	.font800 {
		font-weight: 800;
	}
	
	.fontw {
		font-weight: bold;
	}
	
	.fontc {
		color: white;
	}
	
	.left {
		display: flex;
		align-items: center;
	}
</style>